import requestApi from "../../../../utils/request"
Page({

  data: {
    // 写错了订单类型：all => 全部，nopay=>待支付, nosend=>待发货, noget=>待收货, nocomment=>待评价
    tabs: [
      { key: 'all', text: '全部' },
      { key: 'nopay', text: '待付款', info: '' },
      { key: 'nosend', text: '待发货', info: '' },
      { key: 'noget', text: '待收货', info: '' },
      { key: 'nocomment', text: '已完成', info: '' },
    ],
    page: {
      page: 1,
      per_page: 3,
    },
    curTab: 'all',
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg:
      'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: -1,
  },

  onLoad(query) {
    let status = query.status
    this.setData({
      status: query.status
    })
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : 'all';
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },
  restInit(status) {
    console.log(status)
    this.setData({
      orderList: [],
      page: {
        page: 1
      }
    });
    this.init(this.data.curTab)
  },
  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onReachBottom() {
    if (this.data.listLoading === 0) {
      const { page } = this.data.page
      console.log(page)
      this.setData({
        page: {
          page: page + 1
        }
      })

      this.init(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    this.setData({ pullDownRefreshing: true });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({ pullDownRefreshing: false });
        callback && callback();
      })
      .catch((err) => {
        this.setData({ pullDownRefreshing: false });
        Promise.reject(err);
      });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    // all => 全部，nopay=>待支付, nosend=>待发货, noget=>待收货, nocomment=>待评价
    const buttonTypeArr = [
      {
        class: 'nopay',
        name: '待支付',
        list: [
          {
            primary: false,
            type: 2,
            class: 'nopay',
            name: '取消订单',
          },
          {
            primary: true,
            type: 1,
            class: 'nopay',
            name: '立即支付'
          }
        ]
      },
      {
        class: 'nosend',
        name: '待发货',
        list: [
          {
            primary: false,
            type: 4,
            class: 'nocomment',
            name: '申请售后'
          },
          // {
          //   primary: true,
          //   class: 'nosend',
          //   type: 9,
          //   name: '再次购买',
          // },
        ]
      },
      {
        class: 'noget',
        name: '待收货',
        list: [
          {
            name: '查看物流',
            class: 'noget',
            primary: false,
            type: 8,
          },
          {
            primary: true,
            type: 3,
            class: 'noget',
            name: '确认收货',
          },
        ]
      },
      {
        class: 'nocomment',
        name: '待评价',
        list: [
          {
            primary: false,
            type: 4,
            class: 'nocomment',
            name: '申请售后'
          },
          {
            primary: true,
            class: 'nocomment',
            type: 6,
            name: '立即评价'
          },
        ]
      },
      {
        class: 'cancel',
        list: []
      }
    ]

    const { page } = this.data
    const par = {
      type: status,
      page: page.page,
      per_page: page.per_page
    }
    requestApi.get('shopro/order/index', par, true).then(res => {
      let orderList = [];
      if (res && res.data && res.data.data) {
        orderList = (res.data.data || []).map((order) => {
          let buttonOr = []
          buttonTypeArr.forEach((e) => {
            if (e.class == order.status_code) {
              e.list.forEach(n => {
                buttonOr.push(n)
              })
            }
          })
          return {
            id: order.id,
            orderNo: order.order_sn,
            parentOrderNo: order.parentOrderNo,
            storeId: order.storeId,
            storeName: order.storeName,
            status: order.status_code,
            statusDesc: order.status_desc,
            amount: order.total_amount * 100,
            totalAmount: order.goods_original_amount * 100,
            // logisticsNo: order.logisticsVO.logisticsNo,
            createTime: order.createTime,
            goodsList: (order.item || []).map((goods) => ({
              id: goods.id,
              thumb: goods.goods_image,
              title: goods.goods_title,
              skuId: goods.skuId,
              spuId: goods.spuId,
              specs: (goods.specifications || []).map(
                (spec) => spec.specValue,
              ),
              price: goods.goods_price * 100,
              originalPrice: goods.goods_original_price * 100,
              num: goods.goods_num,
              titlePrefixTags: goods.tagText ? [{ text: goods.tagText }] : [],
            })),
            buttons: buttonOr,
            groupInfoVo: order.groupInfoVo,
            freightFee: order.freightFee,
          };
        });
        this.setData({
          orderList: this.data.orderList.concat(orderList),
          listLoading: orderList.length > 0 ? 0 : 2,
        });
      }
    })
    // this.refreshList(status);
  },

  // getOrderList(statusCode = -1, reset = false) {
  //   const params = {
  //     parameter: {
  //       pageSize: this.page.size,
  //       pageNum: this.page.num,
  //     },
  //   };
  //   if (statusCode !== -1) params.parameter.orderStatus = statusCode;
  //   this.setData({ listLoading: 1 });
  //   return fetchOrders(params)
  //     .then((res) => {
  //       this.page.num++;
  //       let orderList = [];
  //       if (res && res.data && res.data.orders) {
  //         orderList = (res.data.orders || []).map((order) => {
  //           return {
  //             id: order.orderId,
  //             orderNo: order.orderNo,
  //             parentOrderNo: order.parentOrderNo,
  //             storeId: order.storeId,
  //             storeName: order.storeName,
  //             status: order.orderStatus,
  //             statusDesc: order.orderStatusName,
  //             amount: order.paymentAmount,
  //             totalAmount: order.totalAmount,
  //             logisticsNo: order.logisticsVO.logisticsNo,
  //             createTime: order.createTime,
  //             goodsList: (order.orderItemVOs || []).map((goods) => ({
  //               id: goods.id,
  //               thumb: cosThumb(goods.goodsPictureUrl, 70),
  //               title: goods.goodsName,
  //               skuId: goods.skuId,
  //               spuId: goods.spuId,
  //               specs: (goods.specifications || []).map(
  //                 (spec) => spec.specValue,
  //               ),
  //               price: goods.tagPrice ? goods.tagPrice : goods.actualPrice,
  //               num: goods.buyQuantity,
  //               titlePrefixTags: goods.tagText ? [{ text: goods.tagText }] : [],
  //             })),
  //             buttons: order.buttonVOs || [],
  //             groupInfoVo: order.groupInfoVo,
  //             freightFee: order.freightFee,
  //           };
  //         });
  //       }
  //       return new Promise((resolve) => {
  //         if (reset) {
  //           this.setData({ orderList: [] }, () => resolve());
  //         } else resolve();
  //       }).then(() => {
  //         this.setData({
  //           orderList: this.data.orderList.concat(orderList),
  //           listLoading: orderList.length > 0 ? 0 : 2,
  //         });
  //       });
  //     })
  //     .catch((err) => {
  //       this.setData({ listLoading: 3 });
  //       return Promise.reject(err);
  //     });
  // },

  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  onTabChange(e) {
    const { value } = e.detail;
    this.setData({
      curTab: value,
    });
    this.setData({ orderList: [] });
    this.setData({
      page: {
        page: 1
      }
    })
    this.init(value);

  },

  getOrdersCount() {
    // return fetchOrdersCount().then((res) => {
    //   const tabsCount = res.data || [];
    //   const { tabs } = this.data;
    //   tabs.forEach((tab) => {
    //     const tabCount = tabsCount.find((c) => c.tabType === tab.key);
    //     if (tabCount) {
    //       tab.info = tabCount.orderNum;
    //     }
    //   });
    //   this.setData({ tabs });
    // });
  },

  refreshList(status = -1) {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({ curTab: status, orderList: [] });
    console.log(status)
    // addons/shopro/order/index

    // return Promise.all([
    //   this.getOrderList(status, true),
    //   this.getOrdersCount(),
    // ]);
  },

  onRefresh() {

    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    const { order } = e.currentTarget.dataset;
    const orderNo = {
      order_sn: order.orderNo,
      id: order.id
    }
    wx.navigateTo({
      url: `/service/shoppingMall/Order/order-detail/index?orderNo=${JSON.stringify(orderNo)}`,
    });
  },
});
